package com.example.smartcity1.my;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.example.smartcity1.R;
import com.example.smartcity1.bean.MsgCodeBean;
import com.example.smartcity1.bean.MyPasswordPutBean;
import com.example.smartcity1.network.RetrofitClient;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyPasswordActivity extends AppCompatActivity {

    private EditText myPasswordOld;
    private EditText myPasswordNew;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_password);
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setTitle("修改密码");
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        initView();
        SharedPreferences user = getSharedPreferences("user",MODE_PRIVATE);
        button.setOnClickListener(v -> {
            String oldPwd = myPasswordOld.getText().toString();
            String newPwd = myPasswordNew.getText().toString();
            MyPasswordPutBean putBean = new MyPasswordPutBean(user.getString("userId","1"),oldPwd,newPwd);
            RetrofitClient.appService().getMyPasswordData(user.getString("token",""),putBean).enqueue(new Callback<MsgCodeBean>() {
                @Override
                public void onResponse(Call<MsgCodeBean> call, Response<MsgCodeBean> response) {
                    MsgCodeBean msgCodeBean = response.body();
                    if (msgCodeBean != null && msgCodeBean.getCode() == 200) {
                        Toast.makeText(MyPasswordActivity.this, "操作成功", Toast.LENGTH_SHORT).show();
                        SharedPreferences.Editor edit = user.edit();
                        edit.putString("password",newPwd);
                        edit.apply();
                        finish();
                    } else {
                        Toast.makeText(MyPasswordActivity.this, "操作失败,请检查密码", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<MsgCodeBean> call, Throwable t) {

                }
            });
        });
    }

    private void initView() {
        myPasswordOld = findViewById(R.id.my_password_old);
        myPasswordNew = findViewById(R.id.my_password_new);
        button = findViewById(R.id.button);
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return super.onSupportNavigateUp();
    }
}